#include "fpga-common.h"
#include "fpga-private.h"
#include "interface/protocal-otdr.h"

#include <stdio.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <stdlib.h>

// void do_fpga_power(int on_off);


/*
 * 1 点亮LED；0关闭LED，另外还有hook shell
 */
static void do_fpga_power(int on_off)
{
    char  strcmd[256];
    FILE *fp;

    snprintf(strcmd, sizeof(strcmd), "/sys/class/gpio/%s/value", env_dev_led_run);
    fp = fopen(strcmd, "w");
    if (fp) {

	fprintf(fp, "%d", on_off);
	fclose(fp);
    }
    else {
	// printf("没有IO\r\n");
    }


    // 其他shell
    switch (on_off) {
    case 1:
	snprintf(strcmd, sizeof(strcmd), "/app/do_otdr_test_start.sh");
	break;
    case 0:
	snprintf(strcmd, sizeof(strcmd), "/app/do_otdr_test_finish.sh");
	break;
    }

    if ((access(strcmd, F_OK)) != -1) {
	// printf("文件存在\r\n");
	int ret = system(strcmd);
    }
    else {
	// printf("no文件存在\r\n");
    }
}


static int this_suspend(struct fpga_dev *dev)
{
    do_fpga_power(0);
    // printf("实现了吗 %s\r\n ", __FUNCTION__);
    return 0;
}
static int this_resume(struct fpga_dev *dev)
{
    // printf("实现了吗 %s\r\n ", __FUNCTION__);
    do_fpga_power(1);
    return 0;
}

// 这个东西没有任何用，主要为了注册电源管理，目前电源管理没有分离
// 使用以后再说
static struct priv_otdr_data data_32k = {
    .cache_len   = 32000 * 4 + 4000,
    .sample_byte = 32 * 1000 * 4,
};

static struct fpga_if pm_interface = {
    DEFAULT_FPGA_IF,
    .pfun_probe      = cb_fpga_otdr_probe,
    .pfun_release    = cb_fpga_otdr_release,
    .private_data    = &data_32k,
    .name            = "this-pm",
    .pfun_start      = cb_fpga_otdr_start,
    .pfun_isfinish   = cb_fpga_otdr_isfinish,
    .pfun_stop       = cb_fpga_otdr_stop,
    .pfun_set_gpio   = none_set_gpio,
    .pfun_get_gpio   = none_get_gpio,
    .pfun_version    = com_fpga_version,
    .pfun_suspend    = this_suspend,
    .pfun_resume     = this_resume,
    .pfun_read_frame = cb_fpga_read_otdr_data,
    .pfun_write_regs = cb_fpga_otdr_write_regs,
};


static void __attribute__((constructor(INIT_BSP))) this_init()
{
    fpga_if_register(&pm_interface);
}